package com.hkccommunity.controller;


import com.alibaba.fastjson.JSON;
import com.hkccommunity.common.Code;
import com.hkccommunity.common.R;
import com.hkccommunity.dto.AnswerChildDto;
import com.hkccommunity.dto.AnswerDto;
import com.hkccommunity.dto.AnswerParentDto;
import com.hkccommunity.dto.ProblemDto;
import com.hkccommunity.entity.AnswerChild;
import com.hkccommunity.entity.AnswerParent;
import com.hkccommunity.entity.Problem;
import com.hkccommunity.entity.User;
import com.hkccommunity.service.AnswerChildService;
import com.hkccommunity.service.AnswerParentService;
import com.hkccommunity.service.ProblemService;
import com.hkccommunity.service.UserService;
import com.hkccommunity.service.impl.AnswerChildServiceImpl;
import com.hkccommunity.service.impl.AnswerParentServiceImpl;
import com.hkccommunity.service.impl.ProblemServiceImpl;
import com.hkccommunity.service.impl.UserServiceImpl;
import com.hkccommunity.util.DateConversionUtil;
import com.hkccommunity.util.JsonSwitchUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/answer/*")
public class AnswerController extends BaseController{

    private AnswerParentService parentService = new AnswerParentServiceImpl();
    private AnswerChildService childService = new AnswerChildServiceImpl();
    private UserService userService = new UserServiceImpl();

    /**
     * 构建回答页面数据模型
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void getAnswer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取问题dto对象
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        ProblemDto problemDto = JSON.parseObject(line, ProblemDto.class);
        System.out.println(problemDto);


        //创建回答页面整体对象
        AnswerDto answerDto = new AnswerDto();
        answerDto.setProblemDto(problemDto);

        Long problemId = problemDto.getProblemId();



        //查找该id下的回答集合
        List<AnswerParent> answerParentList = parentService.getAnswerByProblemId(problemId);

        answerParentList.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));

        List<AnswerParentDto> parentDtoList = new ArrayList<>();

        R r = new R();
        answerParentList.forEach(answerParent -> {
            //构建父类模型
            AnswerParentDto answerParentDto = new AnswerParentDto();
            try {
                BeanUtils.copyProperties(answerParentDto,answerParent);
            } catch (IllegalAccessException e) {
                r.setCode(Code.POST_ERROR);
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                r.setCode(Code.POST_ERROR);
                throw new RuntimeException(e);
            }
            //查找父类回答的创建人
            User createParentUser = userService.getUserById(answerParent.getCreateUser());
            answerParentDto.setUserInfo(createParentUser);


            //查找父类下的子类回答
            List<AnswerChild> answerChildList = childService.getAnswerChildByParentId(answerParent.getAnswerId());
            //构造answerChildDto
            List<AnswerChildDto> childDtoList = new ArrayList<>();

            //循环子类集合，对childDto进行赋值
            answerChildList.forEach(answerChild -> {
                answerChild.setCreateTime(DateConversionUtil.dateConversion(answerChild.getCreateTime()));
                AnswerChildDto childDto = new AnswerChildDto();
                try {
                    BeanUtils.copyProperties(childDto,answerChild);
                } catch (IllegalAccessException e) {
                    r.setCode(Code.POST_ERROR);
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    r.setCode(Code.POST_ERROR);
                    throw new RuntimeException(e);
                }
                //创建回答的人
                User createUser = userService.getUserById(answerChild.getCreateUser());

                //接收回答的人
                User acceptUser = userService.getUserById(answerChild.getAcceptUser());
//                System.out.println(acceptUser);

                childDto.setSender(createUser);
                childDto.setReceiver(acceptUser);
                childDtoList.add(childDto);
            });
            //父类模型添加子类回答集合
            answerParentDto.setAnswerChildDtoList(childDtoList);

            parentDtoList.add(answerParentDto);
        });

        answerDto.setAnswerParentDtoList(parentDtoList);


        if (r.getCode() == null){
            r.setCode(Code.POST_SUCCESS);
            r.setData(answerDto);
        }else {
            r.setMessage("500 系统出错！！！");
        }

        System.out.println(r);
        JsonSwitchUtil.toJsonSting(req,resp,r);
    }

    public void addParent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();

        //json转换
        AnswerParent answerParent = JSON.parseObject(line, AnswerParent.class);

        answerParent.setCreateUser(user.getId());
        answerParent.setCreateTime(DateConversionUtil.dateToString());
        answerParent.setDelete(0);
        answerParent.setLike(0L);

//        System.out.println(answerParent);

        int i = parentService.addAnswerParent(answerParent);

        R r = new R();


        if(i>0){
            r.setCode(Code.POST_SUCCESS);
            r.setMessage("发送成功~~~");
        }else {
            r.setCode(Code.POST_ERROR);
            r.setMessage("发送失败！！！");
        }
        JsonSwitchUtil.toJsonSting(req,resp,r);
    }


    public void addChild(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        BufferedReader reader = req.getReader();
        String line = reader.readLine();
        AnswerChild answerChild = JSON.parseObject(line, AnswerChild.class);


        answerChild.setCreateUser(user.getId());
        answerChild.setCreateTime(DateConversionUtil.dateToString());
        answerChild.setLike(0L);
        answerChild.setDelete(0);
//        System.out.println(answerChild);

        R r = new R();

        int i = childService.addAnswerChild(answerChild);
        if (i > 0){
            r.setCode(Code.POST_SUCCESS);
            r.setMessage("发送成功");
        }else {
            r.setCode(Code.POST_ERROR);
            r.setMessage("发送失败！！！");
        }
        JsonSwitchUtil.toJsonSting(req,resp,r);

    }
}
